﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;

namespace OF.JsonRpc.Gateway
{
    internal class GatewayFactory
    {
        private static IGateway[] _gateways;
        private static object locker = new object();

        public static IGateway[] GetGateways()
        {
            lock (locker)
            {
                if (_gateways != null)
                    return _gateways;

                List<IGateway> gateways = new List<IGateway>();

                var jsonrpcConfigPath = AppDomain.CurrentDomain.BaseDirectory + "\\jsonrpc.config";

                XmlDocument jsonrpcDoc = new XmlDocument();
                jsonrpcDoc.Load(jsonrpcConfigPath);

                if (jsonrpcDoc["jsonrpc"] != null && jsonrpcDoc["jsonrpc"]["gateways"] != null)
                {
                    foreach (XmlNode gatewayNode in jsonrpcDoc["jsonrpc"]["gateways"].ChildNodes)
                    {
                        try
                        {
                            loadGatway(gatewayNode, gateways);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex);
                        }
                    }
                }
                _gateways = gateways.ToArray();
                return _gateways;
            }

        }

        private static void loadGatway(XmlNode gatewayNode, List<IGateway> gateways)
        {
            if (!"add".Equals(gatewayNode.Name, StringComparison.InvariantCultureIgnoreCase))
                return;

            if (gatewayNode.Attributes != null)
            {
                string gatewayClassName = gatewayNode.Attributes["className"].Value;
                var gatewayType = Type.GetType(gatewayClassName);
                if (gatewayType == null)
                    throw new TypeLoadException(string.Format("JsonRpc gateway type '{0}' load failed, maybe this class doesn't exist", gatewayClassName));
                var instance = (IGateway)Activator.CreateInstance(gatewayType);
                instance.Attributes = new Dictionary<string, string>();
                foreach (XmlAttribute attrib in gatewayNode.Attributes)
                {
                    if ("className".Equals(attrib.Name))
                        continue;
                    instance.Attributes[attrib.Name] = attrib.Value;
                }
                gateways.Add(instance);
            }
        }
    }
}
